var mainTable;
window.thirdPartyFormAPI.registerEvent('afterFormFieldChange',function(params) {

	var formName=parent.$("#formtitle").val();//表单中文名
	try{						
		var display=params.display;
		var getFormData = window.thirdPartyFormAPI.getFormData();

		customControlDataBack(formName, getFormData, params)
		//主表数据
		mainTable = getFormData.formData.tableInfo.formmain.tableName;
		//var field0011 = getFormData.formmains[mainTable].field0011;
		//明细表数据
		var records = getFormData.formsons.front_formson_4.records;
		var size = getFormData.formsons.front_formson_4.records.length;
		var unit = getFormData.formmains[mainTable].field0106.value;
		//var errorTip = getFormData.formmains[mainTable].field0071.value;
		//records[i].lists.field0018.value;
		//records[i].lists.field0019.value;
		if(display==('出生年月')){
			if(!Date.prototype.isDate(params.value)){
				return ;
			}
			add18Year(params.value, records);
		} else if (display==('工作教育经历起始年月')){
			if(!Date.prototype.isDate(params.value)){
				return ;
			}
			var hasToNow = false;
			var isContinue = false;
			for(var i = 0; i < size; i++){
				if(records[i].recordId != params.recordId){
					var errorTip = getFormData.formmains[mainTable].field0071.value;
					if(startIsContinue(params.value, records[i].lists, errorTip, records[i].recordId)){
						isContinue = true;
					}
				} else if(i == 0){
					isContinue = true;
				}
				if(records[i].lists.field0069.showValue == '是'){
					hasToNow = true;
				}
			}
			var errorTip = getFormData.formmains[mainTable].field0071.value;
			if(isContinue){
				updateTip(errorTip, "|start"+params.recordId+"|", false);
			} else {
				updateTip(errorTip, "|start"+params.recordId+"|", true);
			}
			errorTip = getFormData.formmains[mainTable].field0071.value;
			if(hasToNow){
				updateTip(errorTip, "toNow", false);
			} else {
				updateTip(errorTip, "toNow", true);
			}
		} else if(display=='工作教育金额终止年月'){
			if(params.value == ''){
				updateTip(errorTip, "|"+params.recordId+"end|", false);
			}
			if(!Date.prototype.isDate(params.value)){
				return ;
			}
			var hasToNow = false;
			var isContinue = false;
			for(var i = 0; i < size; i++){
				if(records[i].recordId != params.recordId){
					var errorTip = getFormData.formmains[mainTable].field0071.value;
					if(endIsContinue(params.value, records[i].lists, errorTip, records[i].recordId)){
						isContinue = true;
					}
				} else if(i == size-1){
					isContinue = true;
				}
				if(records[i].lists.field0069.showValue == '是'){
					hasToNow = true;
				}
			}
			var errorTip = getFormData.formmains[mainTable].field0071.value;
			if(isContinue){
				updateTip(errorTip, "|"+params.recordId+"end|", false);
			} else {
				updateTip(errorTip, "|"+params.recordId+"end|", true);
			}
			errorTip = getFormData.formmains[mainTable].field0071.value;
			if(hasToNow){
				updateTip(errorTip, "toNow", false);
			} else {
				updateTip(errorTip, "toNow", true);
			}
		} else if(display=='是否至今'){
			var hasToNow = false;
			for(var i = 0; i < size; i++){
				if(records[i].lists.field0069.showValue == '是'){
					hasToNow = true;
				}
			}
			var errorTip = getFormData.formmains[mainTable].field0071.value;
			if(hasToNow){
				updateTip(errorTip, "toNow", false);
			} else {
				updateTip(errorTip, "toNow", true);
			}
		} else if(display == '学校及单位名称'){
			var hasUnit = false;
			for(var i = 0; i < size; i++){
				if(records[i].lists.field0069.showValue == '是'
					&& records[i].lists.field0020.showValue == unit){
					hasUnit = true;
				}
			}
			var errorTip = getFormData.formmains[mainTable].field0108.value;
			if(hasUnit){
				updateTip2(errorTip, "nowUnit", false);
			} else {
				updateTip2(errorTip, "nowUnit", true);
			}
		}
	}catch(err){}
});
	/**
	 * 生日加18岁，并放入重复表第一行的开始时间
	 * @param birthValue
	 */
	function add18Year(birthValue, records){
		var date = new Date(birthValue);
		date.setYear(date.getFullYear()+18);//加18年
		var _dateToStr=date.format('yyyy-MM-dd');
		var _dateCN = date.format('yyyy年MM月');
		if(records[0].lists.field0018.value != _dateToStr
			|| records[0].lists.field0018.value==''){
			/*var _fv = {
				"tableName" : getFormData.formsons.front_formson_4.tableName,
				"tableCategory" : "formson",
				"updateData" : {},
				"updateRecordId" : getFormData.formsons.front_formson_4.records[0].recordId
			};
			_fv.updateData["field0018"] = {
				"showValue" : _dateCN,
				"showValue2" : _dateToStr,
				"value" : _dateToStr
			};
			window.thirdPartyFormAPI.backfillFormControlData(_fv);*/
			records[0].lists.field0018.value=_dateToStr;
			records[0].lists.field0018.valueId=_dateToStr;
			records[0].lists.field0018.showValue=_dateCN;
		}
	}
	
	/**
	 * 
	 * @param time
	 * @param lists
	 */
	function startIsContinue(timeStr, lists, errorTip, recordId){
		var time = new Date(timeStr);
		if(lists.field0069.showValue != '是'){
			var startStr = lists.field0018.value;
			var endStr = lists.field0019.value;
			if(Date.prototype.isDate(endStr)){
				if(notMoreThan3Months(endStr, timeStr)){
					updateTip(errorTip, "|"+recordId+"end|", false);
					return true;
				} 
				if(Date.prototype.isDate(startStr)) {
					var start = new Date(startStr);
					var end = new Date(endStr);
					if(start.getTime() <= time.getTime()
							&& time.getTime() <= end.getTime()){
						return true;
					}
				}
			}
		} else if(lists.field0069.showValue == '是'){
			var startStr = lists.field0018.value;
			if(Date.prototype.isDate(startStr)){
				var start = new Date(startStr);
				if(time.getTime() >= start.getTime()){
					return true;
				}/* else {
					time.setMonth(time.getMonth() + 3);
					if(time.getTime() >= start.getTime()){
						return true;
					}
				}*/
			}
			updateTip(errorTip, "|"+recordId+"end|", false);
		}
		return false;
	}
	
	function endIsContinue(timeStr, lists, errorTip, recordId){
		var time = new Date(timeStr);
		if(lists.field0069.showValue != '是'){
			var startStr = lists.field0018.value;
			var endStr = lists.field0019.value;
			if(Date.prototype.isDate(startStr)){
				if(notMoreThan3Months(timeStr, startStr)){
					updateTip(errorTip, "|start"+recordId+"|", false);
					return true;
				} 
				if(Date.prototype.isDate(endStr)){
					var start = new Date(startStr);
					var end = new Date(endStr);
					if(start.getTime() <= time.getTime()
							&& time.getTime() <= end.getTime()){
						return true;
					}
				}
			}
		} else if(lists.field0069.showValue == '是'){
			var startStr = lists.field0018.value;
			if(Date.prototype.isDate(startStr)){
				var start = new Date(startStr);
				if(notMoreThan3Months(timeStr, startStr)){
					updateTip(errorTip, "|start"+recordId+"|", false);
					return true;
				} else if(time.getTime() >= start.getTime()){
					return true;
				}
			}
		}
		return false;
	}
	/**
	 * 校验时间超过3个月
	 * @param start
	 * @param end
	 * @param errorTip
	 * @param recordId
	 */
	function notMoreThan3Months(start, end){
		var _start = new Date(start);
		var _end = new Date(end);
		_start.setMonth(_start.getMonth() + 3);
		if(_start.getTime() >= _end.getTime()){
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * 更新异常提示
	 * @param errorTip
	 * @param content
	 * @param isAdd
	 */
	function updateTip(errorTip, content, isAdd){
		var _fv_flag={"tableName" : mainTable,  
				"tableCategory" : "formmain",  
				"updateData" : {}
			};
		if(isAdd){
			if(errorTip.indexOf(content) < 0){
				errorTip += content;
			} else {
				isAdd = false;
			}
		} else {
			if(errorTip.indexOf(content) >= 0){
				errorTip = errorTip.replace(content, "");
				isAdd = true;
			}
		}
		if(isAdd){
			_fv_flag.updateData["field0071"] = {"showValue2":	errorTip,"value":	errorTip};
			window.thirdPartyFormAPI.backfillFormControlData(_fv_flag);
		}
	}
	
	function updateTip2(errorTip, content, isAdd){
		var _fv_flag={"tableName" : mainTable,  
				"tableCategory" : "formmain",  
				"updateData" : {}
			};
		if(isAdd){
			if(errorTip.indexOf(content) < 0){
				errorTip += content;
			} else {
				isAdd = false;
			}
		} else {
			if(errorTip.indexOf(content) >= 0){
				errorTip = errorTip.replace(content, "");
				isAdd = true;
			}
		}
		if(isAdd){
			_fv_flag.updateData["field0108"] = {"showValue2":	errorTip,"value":	errorTip};
			window.thirdPartyFormAPI.backfillFormControlData(_fv_flag);
		}
	}
	/**
	 * 删除重复行时进行校验
	 */
	function delVaildatRow(){
		try{
			var getFormData = window.thirdPartyFormAPI.getFormData();
			//主表数据
			mainTable = getFormData.formData.tableInfo.formmain.tableName;
			var field0011 = getFormData.formmains[mainTable].field0011;
			var unit = getFormData.formmains[mainTable].field0106.value;
			//明细表数据
			var records = getFormData.formsons.front_formson_4.records;
			var size = getFormData.formsons.front_formson_4.records.length;
			if(Date.prototype.isDate(field0011.value)){
				add18Year(field0011.value, records);
			}
			updateTip("", "", false);
			var hasToNow = false;
			var hasUnit = false;
			for(var j = 0; j < size; j++){
				if(records[j].lists.field0069.showValue == '是'){
					hasToNow = true;
					if(unit == records[j].lists.field0020.value){
						hasUnit = true;
					}
				}
				
				var isStartContinue = false;
				var isEndContinue = false;
				var params = records[j].lists.field0018;
				if(Date.prototype.isDate(params.value)){
					for(var i = 0; i < size; i++){
						if(records[i].recordId != params.recordId){
							var errorTip = getFormData.formmains[mainTable].field0071.value;
							if(startIsContinue(params.value, records[i].lists, errorTip, records[i].recordId)){
								isStartContinue = true;
							}
						} else if(i == 0){
							isStartContinue = true;
						}
					}
					var errorTip = getFormData.formmains[mainTable].field0071.value;
					if(isStartContinue){
						updateTip(errorTip, "|start"+params.recordId+"|", false);
					} else {
						updateTip(errorTip, "|start"+params.recordId+"|", true);
					}
				}
				
				params = records[j].lists.field0019;
				if(params.value == ''){
					updateTip(errorTip, "|"+params.recordId+"end|", false);
				} else if(Date.prototype.isDate(params.value)){
					for(var i = 0; i < size; i++){
						if(records[i].recordId != params.recordId){
							var errorTip = getFormData.formmains[mainTable].field0071.value;
							if(endIsContinue(params.value, records[i].lists, errorTip, records[i].recordId)){
								isEndContinue = true;
							}
						} else if(i == size-1){
							isEndContinue = true;
						}
					}
					var errorTip = getFormData.formmains[mainTable].field0071.value;
					if(isEndContinue){
						updateTip(errorTip, "|"+params.recordId+"end|", false);
					} else {
						updateTip(errorTip, "|"+params.recordId+"end|", true);
					}
				}
				
			}
			
			var errorTip = getFormData.formmains[mainTable].field0071.value;
			if(hasToNow){
				updateTip(errorTip, "toNow", false);
			} else {
				updateTip(errorTip, "toNow", true);
			}
			
			errorTip = getFormData.formmains[mainTable].field0108.value;
			if(hasUnit){
				updateTip2(errorTip, "nowUnit", false);
			} else {
				updateTip2(errorTip, "nowUnit", true);
			}
			
		} catch(e){}
	}

    /**
    * kk
	 * 关联表单，自定义控件回填
	 */
	function customControlDataBack(formName, getFormData, params){
    		var _tableName = getFormData.formData.tableInfo.formmain.tableName;
    		var _tableInfo = getFormData.formmains[_tableName];
    		for (var i = 0; i < _configInfo.length; i++) {
    			if(formName == _configInfo[i].tableName){
    			    var _tableCode = _configInfo[i].tableCode;
    			    if(formName == '参会者提名'){
                        var _tempTable = params.value.substr(0,2);
                        if(_tempTable == 'PT'){
                            _tableCode = 'formCode007_3';
                        }else if(_tempTable == 'PP'){
                            _tableCode = 'formCode068_3';
                        }else if(_tempTable == 'EE'){
                            _tableCode = 'formCode067_3';
                        }
    			    }
    				if(params.display == "请选择活动编号"){
    					$.ajax({
    						url:'/seeyon/kkMeetingController.do?method=dataBack',
    						type:'POST',
    						data:{
    							tableCode:_tableCode,
    							activityNo : params.value
    						},
    						async:false,
    						dataType:'json',
    						success:function(result){

    							var _fv={
    									"tableName" : _tableName,
    									"tableCategory" : "formmain",
    									"updateData" : {},
    									"updateRecordId" : ""
    								}
    							var params =[];
    							for (var _field in _tableInfo){
    								if ("5550438035101852361" == _tableInfo[_field].inputType) {
    									var _display = _tableInfo[_field].display;
    									_fv.updateData[_field]={"showValue":result[_display] == undefined?'':result[_display],"showValue2":result[_display] == undefined?'':result[_display],"value":result[_display] == undefined?'':result[_display]};
    									params.push(_fv);
    									// 控件浏览状态数据添加不上。不使用权限
    									if(formName.indexOf("报备") == -1)
    									    _tableInfo[_field].auth="browse";

    								}
    							}
    							window.thirdPartyFormAPI.backfillFormControlData(params);
    						},
    						error:function(){
    							console.log("关联底表，自定义控件数据回写错误！");
    						}
    					 });
    				}
    			}
    		}
//    		if(formName == '参会者提名'){
//                 $('.ico24.related_document_24').remove();
//            }
    	}
	
	// tableName 当前表单名称  ， tableCode 关联数据底表的模板编号
	var _configInfo = [
	                   {tableName:"参会者提名",tableCode:"formCode007"},
	                   {tableName:"PT活动回填new",tableCode:"formCode007_3"},
	                   {tableName:"PT活动报备",tableCode:"formCode007_3"},
	                   {tableName:"SA活动报备",tableCode:"formCode066_3"},
	                   {tableName:"SA活动回填",tableCode:"formCode066_3"},
	                   {tableName:"EE活动报备",tableCode:"formCode067_3"},
	                   {tableName:"EE活动回填",tableCode:"formCode067_3"},
	                   {tableName:"PP活动回填",tableCode:"formCode068_3"},
	                   {tableName:"PP活动报备",tableCode:"formCode068_3"}
	                   ]

//日期转字符串
 var dateToStr = function(formatStr, date){
        formatStr = arguments[0] || "yyyy-MM-dd HH:mm:ss";
        date = arguments[1] || new Date();
        var str = formatStr;   
        var Week = ['日','一','二','三','四','五','六'];  
        str=str.replace(/yyyy|YYYY/,date.getFullYear());   
        str=str.replace(/yy|YY/,(date.getYear() % 100)>9?(date.getYear() % 100).toString():'0' + (date.getYear() % 100));   
        str=str.replace(/MM/,date.getMonth()>9?(date.getMonth() + 1):'0' + (date.getMonth() + 1));   
        str=str.replace(/M/g,date.getMonth());   
        str=str.replace(/w|W/g,Week[date.getDay()]);   
      
        str=str.replace(/dd|DD/,date.getDate()>9?date.getDate().toString():'0' + date.getDate());   
        str=str.replace(/d|D/g,date.getDate());   
      
        str=str.replace(/hh|HH/,date.getHours()>9?date.getHours().toString():'0' + date.getHours());   
        str=str.replace(/h|H/g,date.getHours());   
        str=str.replace(/mm/,date.getMinutes()>9?date.getMinutes().toString():'0' + date.getMinutes());   
        str=str.replace(/m/g,date.getMinutes());   
      
        str=str.replace(/ss|SS/,date.getSeconds()>9?date.getSeconds().toString():'0' + date.getSeconds());   
        str=str.replace(/s|S/g,date.getSeconds());   
      
        return str;   
    }
	
	/**
	 * 获取 moduleId
	 * 给 富文本使用
	 */
	window.tinyModuleId=function() {
		return window.thirdPartyFormAPI.getFormData().formData.content.moduleId ;
	}

